package com.android.djlmapp.activity.kuandai;

import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.adapter.kuandai.KuanDaiLocationAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.MyUsualyDialog;
import com.android.djlmapp.model.kaika.KaiKaHomeInfo;
import com.android.djlmapp.model.kaika.SelectNumInfo;
import com.android.djlmapp.model.kuandai.KuanDaiLocationInfo;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.login.OnceLocationTools;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventCodes;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.refresh_view.pullrecyclerview.PullRecyclerView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 宽带地址
 * 跳转单宽带传   1
 * 跳转加装宽带传 2
 * 跳转智慧沃家传 3
 */
public class KuanDaiLcationActivity extends BaseActivity {

    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.kuandai_address)
    TextView kuandaiAddress;
    @BindView(R.id.kuandai_choose)
    TextView kuandaiChoose;
    @BindView(R.id.kuandai_edit)
    EditText kuandaiEdit;
    @BindView(R.id.kuandai_search)
    TextView kuandaiSearch;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.kuandai_recycler)
    PullRecyclerView kuandaiRecycler;
    private String addressQu; // 定位城市
    private String addressSearch; // 搜索内容
    private String addressNum; // 地区编码
    private KuanDaiLocationAdapter kuanDaiLocationAdapter;
    // 选择完地址进行跳转
    private int kuandai_jump; // 跳转单宽带传 1, 跳转加装宽带传 2, 跳转智慧沃家传 3
    private boolean isLocationSuc = false;
    private boolean isDiQuSuc = false;
    private String kuandaiYeWuType;
    private String addressID;
    private MyUsualyDialog dialog;
    private OnceLocationTools locationTools;
    private List<KaiKaHomeInfo.KdAdressBean.AreaListBean> diQuList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kuan_dai_lcation);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.VISIBLE);
        tvName.setText("宽带地址");
        Bundle bundle = getIntent().getExtras();
        kuandai_jump = bundle.getInt("KUANDAI_JUMP", 1);
        kuandaiYeWuType =bundle.getString("KDTYPE");
        addressQu = bundle.getString("LOCATION_ADDRESS");
        diQuList = (List<KaiKaHomeInfo.KdAdressBean.AreaListBean>) bundle.getSerializable("DIQULIST");

        viewLine.setVisibility(View.GONE);
        dialog = new MyUsualyDialog(KuanDaiLcationActivity.this, R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        kuandaiAddress.setText(addressQu);

//        KuanDaiLcationActivityPermissionsDispatcher.openCameraWithCheck(this);
    }


    private List<SelectNumInfo.PhoneList> listNumData = new ArrayList<>();

    @Override
    protected void initData() {
        kuanDaiLocationAdapter = new KuanDaiLocationAdapter(KuanDaiLcationActivity.this);
        kuanDaiLocationAdapter.setOnItemClickListener(new KuanDaiLocationAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(KuanDaiLocationInfo.ListBean item) {
                switch (kuandai_jump) {
                    case 1:
                        startActivity(new Intent(KuanDaiLcationActivity.this, DanKuanDaiActivity.class)
                                .putExtra("KDTYPE", kuandaiYeWuType)
                                .putExtra("ADDRESS_ID", item.getId())
                                .putExtra("ADDRESS_NOTE", item.getAddress_note())
                                .putExtra("KUANDAI_ADDRESS", item.getAddressname()));
                        break;
                    case 2:
                        startActivity(new Intent(KuanDaiLcationActivity.this, JiaZhuangKuanDaiActivity.class)
                                .putExtra("KDTYPE", kuandaiYeWuType)
                                .putExtra("ADDRESS_ID", item.getId())
                                .putExtra("ADDRESS_NOTE", item.getAddress_note())
                                .putExtra("KUANDAI_ADDRESS", item.getAddressname()));
                        break;
                    case 3:
                        startActivity(new Intent(KuanDaiLcationActivity.this, ZhiHuiWoJiaActivity.class)
                                .putExtra("KDTYPE", kuandaiYeWuType)
                                .putExtra("ADDRESS_ID", item.getId())
                                .putExtra("ADDRESS_NOTE", item.getAddress_note())
                                .putExtra("KUANDAI_ADDRESS", item.getAddressname()));
                        break;
                }
            }
        });
        // 设置可以加载
        kuandaiRecycler.enableLoadMore(false);
        // 设置Adapter
        kuandaiRecycler.setColorSchemeResources(R.color.colorAccent);
        kuandaiRecycler.enablePullRefresh(false); // 禁止刷新
        kuandaiRecycler.setAdapter(kuanDaiLocationAdapter);
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case EventCodes.EventKuanDaiCode.A:
                finish();
                break;
        }
    }

    @OnClick({R.id.kuandai_address, R.id.kuandai_choose, R.id.kuandai_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.kuandai_address:
//                String locationStr = kuandaiAddress.getText().toString().trim();
//                if (locationStr.contains("定位")) {
//                    kuandaiAddress.setEnabled(true);
//                    KuanDaiLcationActivityPermissionsDispatcher.openCameraWithCheck(this);
//                } else {
//                    kuandaiAddress.setEnabled(false);
//                }
                break;
            case R.id.kuandai_choose:
                Intent intent = new Intent(KuanDaiLcationActivity.this, KuanDaiDiQuActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("AddressQu", addressQu);
                bundle.putSerializable("DIQULIST", (Serializable) diQuList);
                intent.putExtras(bundle);
                startActivityForResult(intent, 111);
                break;
            case R.id.kuandai_search:
//                if (isLocationSuc) {
                if (isDiQuSuc) {
                    addressQu = kuandaiAddress.getText().toString().trim();
                    addressSearch = kuandaiEdit.getText().toString().trim();
                    getData(addressQu, addressSearch);
                } else {
                    ToastUtils.showShortToast(KuanDaiLcationActivity.this, "请先选择地区");
                }
//                } else {
//                    ToastUtils.showShortToast(KuanDaiLcationActivity.this, "尚未定位成功,请稍后再试");
//                }
                break;
        }
    }

    /**
     * 宽带获取地址
     *
     * @param addressQu
     * @param addressSearch
     */
    private void getData(String addressQu, String addressSearch) {
        kuanDaiLocationAdapter.clear();
        dialog.show();
        MyApplication.getInstance().getHttpTools().getKuanDaiLocation(kuandaiYeWuType, addressQu, addressID,
                addressSearch, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        try {
                            parseJson(response.body());
                        } catch (Exception e) {
                            e.printStackTrace();
                            viewLine.setVisibility(View.GONE);
                            ToastUtils.showShortToast(KuanDaiLcationActivity.this, "数据解析异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        kuanDaiLocationAdapter.clear();
                        viewLine.setVisibility(View.GONE);
                        ToastUtils.showShortToast(KuanDaiLcationActivity.this, "网络或服务器错误");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if (kuandaiRecycler != null) {
                            kuandaiRecycler.postDelayed(() -> {
                                kuandaiRecycler.stopLoadMore();
                                kuandaiRecycler.stopRefresh();
                            }, 300);
                        }
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    }
                });
    }

    private void parseJson(String json) {
        Gson gson = new Gson();
        KuanDaiLocationInfo kuanDaiLocationInfo = gson.fromJson(json, KuanDaiLocationInfo.class);
        if (kuanDaiLocationInfo.getCode() == 200) {
            List<KuanDaiLocationInfo.ListBean> list = kuanDaiLocationInfo.getList();
            if (list != null && list.size() > 0) {
                viewLine.setVisibility(View.VISIBLE);
                kuanDaiLocationAdapter.addAll(list);
            } else {
                ToastUtils.showShortToast(KuanDaiLcationActivity.this, "未获取到地址数据");
            }

        } else {
            ToastUtils.showShortToast(KuanDaiLcationActivity.this, kuanDaiLocationInfo.getMsg());
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationTools != null) {
            locationTools.stopLocation();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 111) {
            isDiQuSuc = true;
            addressID = data.getStringExtra("DIQU");
            addressNum = data.getStringExtra("DIQUADDRESS");
            kuandaiChoose.setText(addressNum);
        }
    }

}
